package com.qf.air.interceptor;

import com.qf.air.constants.AirConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 维多利加
 * @Date: 2021/3/25 19:20
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    /**
     * RedisTemplate: 默认情况下，将key和value都转换成byte[]存储到Redis服务
     * StringRedisTemplate：将key和value以字符串的方式存储
     */
    @Autowired
    private StringRedisTemplate redisTemplate;

    //前处理
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String user = null;
        String key = null;
        //1. 从redis中查询用户信息
        //1.1 获取cookie中存放的userKey
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(AirConstants.USER_COOKIE)) {
                    // 获取userKey的value
                    String keySuffix = cookie.getValue();
                    //1.2 通过JedisUtil查询用户信息
                    key = AirConstants.USER_REDIS_PREFIX + keySuffix;
                    user = redisTemplate.opsForValue().get(key);
                    break;
                }
            }
        }

        //2.如果登录了，return true，如果没登陆 return false
        if(user != null){
            redisTemplate.expire(key,AirConstants.USER_TIMEOUT, TimeUnit.SECONDS);
            return true;
        }else{
            response.sendRedirect(request.getContextPath()+"/login.html");
            return false;
        }
    }

    //后处理
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("后处理！");
    }

    //最终处理
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("最终处理！");
    }
}
